﻿<%@ WebHandler Language="C#" Class="ResumeHandler" %>

using System;
using System.Web;
using System.Collections;
using System.Data;
using StarTech.DBUtility;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Web.DynamicData;


public class ResumeHandler : IHttpHandler
{
    AdoHelper ado = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance);
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value))
        if (true)
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
            string flag = Common.NullToEmpty(context.Request["flag"]);

            //任务信息
            string workYear = Common.NullToEmpty(context.Request["workYear"]);
            string skill = Common.NullToEmpty(context.Request["skill"]);
            string addressCode = Common.NullToEmpty(context.Request["addressCode"]);
            string addressTxt = Common.NullToEmpty(context.Request["addressTxt"]);
            string selfIntro = Common.NullToEmpty(context.Request["selfIntro"]);
            string id = Common.NullToEmpty(context.Request["id"]);

            switch (flag.ToLower())
            {
                case "info":
                    context.Response.Write(GetResumeInfo());
                    break;
                case "detail":
                    string mid=Common.NullToEmpty(context.Request["mid"]);
	                memberId = string.IsNullOrEmpty(mid) ? memberId : mid;
                    context.Response.Write(GetResumeDetail());
                    break;
                case "add":
                    context.Response.Write(AddResumeInfo(workYear, skill, addressCode, addressTxt, selfIntro));
                    break;
                case "uppic":
                    if (context.Request.Files.Count == 0)
                    {
                        context.Response.Write("请选择文件");  //代表文件为空
                    }
                    else
                    {
                        context.Response.Write(UploadFile(context.Request.Files[0]));
                    }
                    break;
                case "delpic":
                    context.Response.Write(DeletePic(id));
                    break;
            }
        }
        else
        {
            context.Response.Write("please login");
        }
    }

	private string GetResumeDetail()
	{
        string json = "";

        string strSql = @"select  TrueName,LevelName,headimg,DATEDIFF(year, BirthDay, getdate()) as Age,b.area_name as city, Specialty, Skill, SelfIntroduction,c.ifpass from T_Member_Info a left join T_Base_Area b on a.AddressCode=b.area_id left join T_Member_Pic c on a.MemberId=c.memberId and c.applyType='auth' where a.MemberId=@MemberId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@MemberId",memberId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
        json += "_$$_";
        string strSql2 = @"select applyId,applyPic from t_member_pic where applyType='resume' and MemberId=@MemberId;";
        SqlParameter[] p2 = new SqlParameter[] {
            new SqlParameter("@MemberId",memberId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql2, p2).Tables[0]);
        return json;
	}

	private string GetResumeInfo()
    {
        string json = "";

        string strSql = @"select  AddressCode, AddressDetail, Specialty, Skill, SelfIntroduction, LevelName from T_Member_Info where MemberId=@MemberId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@MemberId",memberId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
        json += "_$$_";
        string strSql2 = @"select applyId,applyPic from t_member_pic where applyType='resume' and MemberId=@MemberId;";
        SqlParameter[] p2 = new SqlParameter[] {
            new SqlParameter("@MemberId",memberId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql2, p2).Tables[0]);
        return json;
    }

    private string AddResumeInfo(string workYear, string skill, string addressCode, string addressTxt, string selfIntro)
    {
        try
        {
            string strSql = "";
            if (string.IsNullOrEmpty(addressCode))
            {
                strSql = "select * from T_Base_Area where CHARINDEX(area_name,@area_name)>0 order by area_level desc";
                SqlParameter[] p2 = new SqlParameter[] { 
                    new SqlParameter("@area_name",addressTxt)
                };
                DataTable dt=ado.ExecuteSqlDataset(strSql, p2).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    addressCode = dt.Rows[0]["area_id"].ToString();
                }
            }
            
            strSql = "update t_member_info set AddressCode=@AddressCode, AddressDetail=@AddressDetail, Specialty=@Specialty, Skill=@Skill, SelfIntroduction=@SelfIntroduction where memberId=@MemberId";
            SqlParameter[] p = new SqlParameter[] {
                new SqlParameter("@MemberId",memberId),
                new SqlParameter("@AddressCode",addressCode),
                new SqlParameter("@AddressDetail",addressTxt),
                new SqlParameter("@Specialty",workYear),
                new SqlParameter("@Skill",skill),
                new SqlParameter("@SelfIntroduction",selfIntro),
            };
            string result=ado.ExecuteSqlNonQuery(strSql, p).ToString();
            return result;
        }
        catch (Exception ex)
        { return "错误：" + ex.Message; }
    }

    private string UploadFile(HttpPostedFile file)
    {
        string fileTail = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
        if (fileTail != ".jpeg" && fileTail != ".jpg" && fileTail != ".png" && fileTail != ".bmp" && fileTail != ".gif")
        {
            return "图片格式不正确";
        }
        if (file.ContentLength > 1024000)
        {
            return "图片不能大于1M";
        }

        //保存文件
        string path = "/upload/resume";
        path += "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd") + "/";
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
        path += DateTime.Now.ToString("HHmmssffff") + fileTail;
        file.SaveAs(HttpContext.Current.Server.MapPath(path));

        //缩略图
        string smallPath = path.Replace(fileTail, "_s" + fileTail);
        bool iscreate = MakeSmallPic(HttpContext.Current.Server.MapPath(path), HttpContext.Current.Server.MapPath(smallPath));
        if (iscreate == false) { smallPath = path; }

        //修改数据库
        string id = IdCreator.CreateId("T_Member_Pic", "applyId");
        string strSql2 = "insert into t_member_pic(applyId,memberId,applyTime,ifPass,applyType,applyPic) values(@applyId,@memberId,@applyTime,@ifPass,@applyType,@applyPic)";
        SqlParameter[] p2 = new SqlParameter[] {
            new SqlParameter("@applyId",id),
            new SqlParameter("@memberId",memberId),
            new SqlParameter("@applyTime",DateTime.Now),
            new SqlParameter("@ifPass",'0'),
            new SqlParameter("@applyType","resume"),
            new SqlParameter("@applyPic",smallPath),
        };
        ado.ExecuteSqlNonQuery(strSql2, p2);
        return id + "_$$_" + smallPath;
    }

    protected bool MakeSmallPic(string oldPicPath, string smallPicPath)
    {
        try
        {
            System.Threading.Thread.Sleep(1000);
            WLWang.MakeThumbnail.MakeToThumbnail(oldPicPath, smallPicPath, 400, 300, "Cut");
            return true;
            // 生成缩略图方法 
            //生成的缩略图稍微比前台显示的图片大点，这样显示的清晰度高点（如前台显示100*150，则生成200*300）
        }
        catch { return false; }
    }

    private string DeletePic(string id)
    {
        string strSql1 = "select applyPic from t_member_pic where applyId=@applyId and MemberId=@MemberId and applyType='resume';";
        SqlParameter[] p1 = new SqlParameter[]
        {
            new SqlParameter("@applyId", id),
            new SqlParameter("@MemberId",memberId),
        };
        string picpath = ado.ExecuteSqlScalar(strSql1, p1).ToString();
        File.Delete(HttpContext.Current.Server.MapPath(picpath));

        string strSql2 = "delete from t_member_pic where applyId=@applyId and MemberId=@MemberId and applyType='resume';;";
        SqlParameter[] p2 = new SqlParameter[]
        {
            new SqlParameter("@applyId", id),
            new SqlParameter("@MemberId",memberId),
        };
        return ado.ExecuteSqlNonQuery(strSql2, p2).ToString();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}